创建索引
构建索引请求
1 | CreateIndexRequest request = new CreateIndexRequest("product"); |
设置分片
1
request.settings(Settings.builder() .put("index.number_of_shards", 3) .put("index.number_of_replicas", 2) );
设置mapping
1
request.mapping( "{\n" + " \"properties\": {\n" + " \"message\": {\n" + " \"type\": \"text\"\n" + " }\n" + " }\n" + "}", XContentType.JSON);
1 | # JSON 参考 |
es新版本不再推荐使用Type,这里不再设置type,不设置默认type为:_doc
除了提供JSON字符串设置mapping外还提供了Map和XContentBuilder方式提供
- 索引别名
在elasticsearch里面给index起一个aliases(别名)能非常优雅的解决两个索引无缝切换的问题。
比如电商的核心商品索引库,除了实时增量数据外,每天都要重建一遍索引,避免index里面的数据和db里面的数据不一致。全量索引重建完再切换1
request.alias(new Alias("product_alias").filter(QueryBuilders.termQuery("user", "kimchy")));
除了单独设置maping()和settings()外还可以调用source()一次性设置。如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30 {
"mappings": {
"properties": {
"user": {
"type": "text",
"analyzer": "ik_max_word",
"search_analyzer": "ik_smart"
},
"title": {
"type": "text",
"analyzer": "ik_max_word",
"search_analyzer": "ik_smart"
},
"desc": {
"type": "text",
"analyzer": "ik_max_word",
"search_analyzer": "ik_smart"
}
}
},
"settings" : {
"index" : {
"number_of_shards" : 2,
"number_of_replicas" : 2
}
},
"aliases":{
"product_alias":{}
}
}
索引的其他可选参数
设置索引创建的超时时间
1
request.setTimeout(TimeValue.timeValueMinutes(2));
设置连接到master(主节点)的超时时间
1
request.setMasterTimeout(TimeValue.timeValueMinutes(1));
创建索引API返回响应之前要等待的活动分片副本数
1
request.waitForActiveShards(ActiveShardCount.from(2));
索引请求返回前需要等待多少个分片写入成功
异步请求
构建listener监听请求
1
2
3
4
5
6
7
8
9
10
11ActionListener<CreateIndexResponse> listener =
new ActionListener<CreateIndexResponse>() {
public void onResponse(CreateIndexResponse createIndexResponse) {
//请求成功的处理逻辑
}
public void onFailure(Exception e) {
//请求失败的处理逻辑
}
};发送请求并监听
1
client.indices().createAsync(request, RequestOptions.DEFAULT, listener);
接收处理响应
1 | //所以节点是否都成功接收请求 |
参考链接:https://www.elastic.co/guide/en/elasticsearch/client/java-rest/7.3/java-rest-high-create-index.html